package com.yuan.base.framework;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.yuan.base.utils.UIUtil;


/**
 */
public abstract class BaseFrameworkFragment extends Fragment {

	private LayoutInflater inflater;
	protected BaseFrameworkActivity context;
	// 标志位，标志已经初始化完成。
	protected boolean isPrepared;
	private View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		this.inflater = inflater;
		checkContext();
		view = inflater.inflate(getLayoutId(), null);
		bindViews();
		isPrepared = true;
		initUI();
		return view;
	}

	protected <T extends View> T findViewById(int id) {
		return view.findViewById(id);
	}

	protected LayoutInflater getInflater() {
		return inflater;
	}

	protected abstract int getLayoutId();

	protected abstract void initUI();

	protected abstract void bindViews();

	public void showToast(String str) {
		UIUtil.showToast(str);
	}

	public void showProgressBar() {
		showProgressBar("正在加载数据,请稍候.");
	}

	protected boolean checkContext() {
		if (context == null) {
			try {
				this.context = (BaseFrameworkActivity) getActivity();
			} catch (Exception e) {
				return false;
			}
		}
		return context != null;
	}

	public void showProgressBar(String content) {
		if (checkContext()) {
			context.showProgressBar(content);
		}
	}

	public void hideProgressBar() {
		if (checkContext()) {
			context.hideProgressBar();
		}
	}

	// 不考虑进度条数量,直接关闭
	public void hideProgressBarAtOnce() {
		if (checkContext()) {
			context.hideProgressBarAtOnce();
		}
	}

	protected String getStringByUI(TextView textView) {
		if (textView != null) {
			return textView.getText().toString();
		}
		return "";
	}

	protected static String getUnNullString(String s, String defalt) {
		return TextUtils.isEmpty(s) ? defalt : s;
	}

	protected static String getUnNullString(String s) {
		return TextUtils.isEmpty(s) ? "" : s;
	}

	protected int getColorBase(int id) {
		return ContextCompat.getColor(context, id);
	}

	protected Drawable getDrawableBase(int id) {
		return ContextCompat.getDrawable(context, id);
	}

	protected void setOnClickListener(int id, View.OnClickListener onClickListener) {
		findViewById(id).setOnClickListener(onClickListener);
	}
}
